package com.chancein.cloud.report.charts.service;

import com.chancein.cloud.ocr.process.OcrProcessApiService;
import com.chancein.cloud.ocr.process.api.impl.OcrProcessApiServiceImpl;
import com.chancein.cloud.report.charts.common.util.DateUtil;
import com.chancein.cloud.report.charts.common.util.FileTool;
import com.chancein.cloud.report.charts.service.template.GenerateDataTemplate;
import com.chancein.cloud.report.charts.service.template.RepairDataTemplate;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.time.YearMonth;

import static com.chancein.cloud.report.charts.common.constant.EsConstant.PAGE_SIZE;
import static com.chancein.cloud.report.charts.config.InitParamConfig.*;

/**
 * 俊哥所需数据生成
 *
 * @author: LiaoZiHao
 * @date: 2023/7/27 13:53
 * Copyright © 2022 Hundsun Technologies Inc. All Rights Reserved
 */
@Slf4j
public class ReportChartsService {
    public static OcrProcessApiService ocrProcessApiService = new OcrProcessApiServiceImpl();
    /**
     * 生成数据
     *
     * @date 2023/8/2 15:36
     * @author liaozihao
     */
    public static void generateData() {
        YearMonth yearMonth = YearMonth.of(Year, Month);
        int days = yearMonth.lengthOfMonth();
        int part = days / ThreadNum;
        int remainder = days % ThreadNum;
        for (int i = 1; i <= ThreadNum; i++) {
            String startTime = DateUtil.fetchStandardDate(((i - 1) * part) + 1);
            String endTime = (i != ThreadNum) ? DateUtil.fetchStandardDate(i * part)
                                              : DateUtil.fetchStandardDate(i * part + remainder);
            String filename = "report_charts_OCR[" + startTime + "to" + endTime + "]";
            new Thread(() -> {
                try {
                    GenerateDataTemplate.exportData(startTime,
                            endTime,
                            FileTool.fileCurrentCount(filename),
                            PAGE_SIZE);
                } catch (IOException e) {
                    log.error("report_charts_OCR[" + startTime + "to" + endTime + "].json 文件导出[失败]");
                    e.printStackTrace();
                }
            }, "Thread_0" + i).start();
        }
        log.info("------------ GenerateData All Thread Start -------------");
    }
    /**
     * 修复原有数据
     *
     * @date 2023/8/4 13:24
     * @author liaozihao
     */
    public static void repairData() {
        for (int i = 1; i <= FileList.size(); i++) {
            String sourceFilename = FileList.get(i - 1);
            String targetFilename = "REPAIR_" + sourceFilename;
            new Thread(() -> RepairDataTemplate.repairExportData(sourceFilename, targetFilename), "Thread_0" + i).start();
        }
        log.info("------------ RepairData All Thread Start -------------");
    }
}
